package com.xm.web.entity;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Collections;
import java.util.List;

/**
 * @author yousj
 * @version 1.0.0
 * @since 2021/8/20 11:30
 */
@Data
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor
public class PageResult<T> {

    private int pageNum = 1;

    private int pageSize = 10;

    private long total;

    private int pages = 1;

    private boolean hasNext;

    private List<T> list;

    public static <T> PageResult<T> of(PageInfo<T> info) {
        return of(info, info.getList());
    }

    public static <T> PageResult<T> of(PageInfo<?> info, List<T> result) {
        if (info == null || result == null) {
            return new PageResult<>();
        }
        return new PageResult<>(info.getPageNum(), info.getPageSize(), info.getTotal(), info.getPages(), info.isHasNextPage(), result);
    }


    public static <T> PageResult<T> of(Long totalCount, Pageable pageable, List<T> data) {
        int totalPage = (int) Math.ceil((float) totalCount / pageable.getPageSize());
        return new PageResult<>(pageable.getPageNum(), pageable.getPageSize(), totalCount, totalPage, pageable.getPageNum() < totalPage, data);
    }

    public static <T> PageResult<T> ofPage(Long totalCount, Pageable pageable, List<T> data) {
        int totalPage = (int) Math.ceil((float) totalCount / pageable.getPageSize());
        List<T> newList = data.subList(pageable.getPageSize() * (pageable.getPageNum() - 1), (int) Math.min((pageable.getPageSize() * pageable.getPageNum()), totalCount));
        return new PageResult<>(pageable.getPageNum(), pageable.getPageSize(), totalCount, totalPage, pageable.getPageNum() < totalPage, newList);
    }

    public static <T> PageResult<T> empty(Pageable pageable) {
        return new PageResult<>(pageable.getPageNum(), pageable.getPageSize(), 0, 0, false, Collections.emptyList());
    }


    public static <T> PageInfo<T> getPageInfo(int currentPage, int pageSize, List<T> list) {
        int total = list.size();
        if (total > pageSize) {
            int toIndex = pageSize * currentPage;
            if (toIndex > total) {
                toIndex = total;
            }
            list = list.subList(pageSize * (currentPage - 1), toIndex);
        }
        Page<T> page = new Page<>(currentPage, pageSize);
        page.addAll(list);
        page.setPages((total + pageSize - 1) / pageSize);
        page.setTotal(total);

        PageInfo<T> pageInfo = new PageInfo<>(page);
        return pageInfo;
    }

}
